package com.sdust.user;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String rememberMe = req.getParameter("rememberMe");

        // 模拟用户数据，实际应用中应该使用数据库
        String validUsername = "user";
        String validPassword = "password";
        System.out.println(username + ": " + password);

        if (username.equals(validUsername) && password.equals(validPassword)) {
            HttpSession session = req.getSession();
            session.setAttribute("username", username);

            // 如果勾选了"Remember Me"，在Cookie中存储用户名和密码
            if ("on".equals(rememberMe)) {
                Cookie usernameCookie = new Cookie("username", username);
                usernameCookie.setMaxAge(7 * 24 * 60 * 60); // 7 days
                resp.addCookie(usernameCookie);

                Cookie passwordCookie = new Cookie("password", password);
                passwordCookie.setMaxAge(7 * 24 * 60 * 60); // 7 days
                resp.addCookie(passwordCookie);
            }

            resp.sendRedirect("welcome.jsp");
        } else {
            resp.sendRedirect("login.jsp");
        }
    }
}
